<template>
  <el-row>
    <el-col :span="24">
      <el-card>
        <el-form :inline="true">
          <el-form-item>
            <el-button type="primary" plain @click="addDialogShow=true">添加</el-button>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-input v-model="condition.name" placeholder="请输入要搜索的姓名" @input="selectByPage(1)"/>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-select
                v-model="condition.status"
                placeholder="请选择是否上架"
                style="width: 150px"
                clearable
                :value-on-clear="null"
                @change="selectByPage(1)"
            >
              <el-option label="上架" value="1"/>
              <el-option label="下架" value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-select
                v-model="condition.parentId"
                placeholder="请选择父分类"
                style="width: 150px"
                clearable
                :value-on-clear="null"
                @change="selectByPage(1)"
            >
              <el-option label="父分类" value="0"/>
              <el-option v-for="(parent,index) in allParent" :key="index" :label="parent.name" :value="parent.id"/>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table :data="pageInfo.list" border>
          <el-table-column prop="id" label="ID"/>
          <el-table-column label="图片" >
            <template #default="scope">
              <el-avatar shape="square" :size="50" :src="SERVER_ADDR +'/category/pic/' + scope.row.pic"/>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称"/>
          <el-table-column prop="dscp" label="描述"/>
          <el-table-column label="父分类">
            <template #default="scope">
              <el-text class="mx-1" type="primary" v-if="scope.row.parent">{{ scope.row.parent.name }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="是否推荐" width="90px" align="center">
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.recom == 1">推荐</el-tag>
              <el-tag type="info" v-if="scope.row.recom == 0">不推荐</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否上架" align="center" >
            <template #default="scope">
              <el-switch v-model="scope.row.status"
                         inline-prompt
                         :inactive-value="0"
                         :active-value="1"
                         style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                         inactive-text="下架"
                         active-text="上架"
                         @change="updateStatus(scope.row)"
              />

            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button size="small" plain type="warning"  @click="selectById(scope.row.id)">
                修改
              </el-button>
              <el-button size="small" plain type="danger" @click="deleteCategory(scope.row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="row-bg" justify="center" style="margin-top: 20px;">
          <el-pagination layout="prev, pager, next" :total="pageInfo.total" :page-size="pageInfo.pageSize"
                         @change="selectByPage"/>
        </el-row>
      </el-card>
    </el-col>
  </el-row>

  <!-- 添加分类框开始 -->
  <el-dialog v-model="addDialogShow" title="添加分类" width="500">
    <el-form>
      <el-form-item label="图片" label-width="20%">
        <el-upload class="avatar-uploader" :action="SERVER_ADDR +'/category/upload'" name="pic" :headers="headers"
                   :show-file-list="false" :before-upload="beforePicUpload" :on-success="picAddUploadSuccess">
          <img v-if="categoryAdd.pic" :src="SERVER_ADDR +'/category/pic/' + categoryAdd.pic" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="categoryAdd.name" placeholder="请输入名称" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="categoryAdd.dscp" placeholder="请输入描述" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="父分类" label-width="20%">
        <el-select v-model="categoryAdd.parentId" placeholder="请选择父分类" clearable :value-on-clear="0"
                   :empty-values="[0]" style="width: 300px">
          <el-option v-for="(category,index) in allParent" :key="index" :label="category.name" :value="category.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐" label-width="20%">
        <el-radio-group v-model="categoryAdd.recom">
          <el-radio label="不推荐" :value="0"/>
          <el-radio label="推荐" :value="1"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架" label-width="20%">
        <el-radio-group v-model="categoryAdd.status">
          <el-radio label="下架" :value="0"/>
          <el-radio label="上架" :value="1"/>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogShow = false">
          取消
        </el-button>
        <el-button type="primary" @click="insert">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加分类框结束 -->

  <!-- 修改分类框开始 -->
  <el-dialog v-model="updateDialogShow" title="修改分类" width="500">
    <el-form>
      <el-form-item label="图片" label-width="20%">
        <el-upload class="avatar-uploader" :action="SERVER_ADDR +'/category/upload'" name="pic" :headers="headers"
                   :show-file-list="false" :before-upload="beforePicUpload" :on-success="picUpdateUploadSuccess">
          <img v-if="categoryUpdate.pic" :src="SERVER_ADDR +'/category/pic/' + categoryUpdate.pic" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="categoryUpdate.name" placeholder="请输入名称" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="categoryUpdate.dscp" placeholder="请输入描述" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="父分类" label-width="20%">
        <el-select v-model="categoryUpdate.parentId" placeholder="请选择父分类" clearable :value-on-clear="0"
                   :empty-values="[0]" style="width: 300px">
          <el-option v-for="(category,index) in allParent" :key="index" :label="category.name" :value="category.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐" label-width="20%">
        <el-radio-group v-model="categoryUpdate.recom">
          <el-radio label="不推荐" :value="0"/>
          <el-radio label="推荐" :value="1"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架" label-width="20%">
        <el-radio-group v-model="categoryUpdate.status">
          <el-radio label="下架" :value="0"/>
          <el-radio label="上架" :value="1"/>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogShow = false">
          取消
        </el-button>
        <el-button type="primary" @click="update">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改分类框结束 -->

</template>

<script setup>
import categoryApi from "@/api/categoryApi.js";
import {computed, ref} from "vue";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import {useTokenStore} from "@/stores/token.js";

const tokenStore = useTokenStore();
const headers = computed(() => {
  const token = tokenStore.tokenStr;
  return{
    token:token
  }
})

//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)
//搜索条件
const condition = ref({
  name: null,
  parentId: null,
  status: null
});

//分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});
//父分类
const allParent = ref([])
//被添加分类信息
const categoryAdd = ref({
  name: null,
  dscp: null,
  pic: null,
  parentId: 0,
  recom: 1,
  status: 1
})
//是否显示添加对话框
const addDialogShow = ref(false);

//被修改分类信息
const categoryUpdate = ref({
  id:null,
  name: null,
  dscp: null,
  pic: null,
  parentId: 0,
  recom: 1,
  status: 1
})
//是否显示修改对话框
const updateDialogShow = ref(false);


//修改状态
function updateStatus(category) {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  categoryApi.updateStatus(category)
      .then(resp => {
        loading.close();
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1500
          })
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 1500
          });
        }
      });
}
//修改分类
function update() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  categoryApi.update(categoryUpdate.value)
      .then(resp => {
        loading.close();
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1500
          })
          updateDialogShow.value = false;
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 1500
          });
        }
      });
}
//根据id查询被修改分类的信息
function selectById(id){
  categoryApi.selectById(id)
      .then(resp => {
        categoryUpdate.value = resp.data;
        updateDialogShow.value=true;
      })
}

//删除
function deleteCategory(id) {
  ElMessageBox.confirm(
      '确认删除该分类?',
      '删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        categoryApi.delete(id)
            .then(resp => {
              if (resp.code == 10000) {
                ElMessage({
                  message: resp.msg,
                  type: 'success',
                  duration: 1500
                })
                selectByPage(pageInfo.value.pageNum);
              } else {
                ElMessage({
                  message: resp.msg,
                  type: 'error',
                  duration: 1500
                });
              }
            })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

//添加分类
function insert() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  categoryApi.inset(categoryAdd.value)
      .then(resp => {
        loading.close();
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1500
          })
          addDialogShow.value = false;
          categoryAdd.value = {
            name: null,
            dscp: null,
            pic: null,
            parentId: 0,
            recom: 1,
            status: 1
          };
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 1500
          });
        }
      });
}

//分页查询
function selectByPage(pageNum) {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  categoryApi.selectByPage(condition.value, pageNum, 5)
      .then(resp => {
        loading.close();
        pageInfo.value = resp.data;

      })
}

//获取所有父分类
function selectAllParent() {
  categoryApi.selectAllParent()
      .then(resp => {
        allParent.value = resp.data;
      })
}

//参数表示选中的图片
function beforePicUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式有误')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2M!')
    return false
  }
  return true
}

//添加图片上传成功的回调
function picAddUploadSuccess(resp) {
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    categoryAdd.value.pic = resp.data;
  } else {
    ElMessage.error(resp.msg);
  }
}
//修改图片上传成功的回调
function picUpdateUploadSuccess(resp) {
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    categoryUpdate.value.pic = resp.data;
  } else {
    ElMessage.error(resp.msg);
  }
}

selectAllParent();
selectByPage(1);
</script>

<style scoped>
.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>